package org.wevil;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.wevil.props.ActiveProp;
import org.wevil.thread.SocketListener;
import org.wevil.util.BeanUtil;

@EnableJpaAuditing
@EnableTransactionManagement
@EnableScheduling
@SpringBootApplication
public class BootApplication {

	public static void main(String[] args) {
		BeanUtil.applicationContext = SpringApplication.run(BootApplication.class, args);

		ActiveProp activeProp = BeanUtil.getBean(ActiveProp.class);
		String active = activeProp.getActive();

		// 生产环境启动监听线程
		if(active.equals("prd")){
			System.out.println("启用线程监听...");
			// 报警控制器监听
			SocketListener alarmControlListener = new SocketListener();
			alarmControlListener.start();
		}
	}

	/**
	 * 定制嵌入式的servlet容器
	 * 在Spring Boot2.0以上配置嵌入式Servlet容器时EmbeddedServletContainerCustomizer类被WebServerFactoryCustomizer替代
	 *
	 * @author wanglei
	 * @since 2023/10/9
	 * */
	@Bean
	public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){
		return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>(){
			//定制嵌入式的servlet容器相关的规则
			@Override
			public void customize(ConfigurableWebServerFactory factory) {
				// 处理全局异常，统一处理页面
				ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST,"/errorPage");
				ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND,"/errorPage");
				ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR,"/errorPage");
				factory.addErrorPages(errorPage400,errorPage404,errorPage500);
			}
		};
	}
}
